import type { RouteRecordRaw } from "vue-router"
import { createRouter } from "vue-router"
import { routerConfig } from "@/router/config"
import { registerNavigationGuard } from "@/router/guard"
// import { flatMultiLevelRoutes } from "./helper"

const Layouts = () => import("@/layouts/index.vue")
const EmptyNav = () => import("@/layouts/components/EmptyNav/index.vue")

/**
 * @name 常驻路由
 * @description 基础路由（无权限限制）
 */
export const constantRoutes: RouteRecordRaw[] = [
  {
    path: "/redirect",
    component: Layouts,
    meta: { hidden: true },
    children: [
      {
        path: ":path(.*)",
        component: () => import("@/pages/redirect/index.vue")
      }
    ]
  },
  {
    path: "/403",
    component: () => import("@/pages/error/403.vue"),
    meta: { hidden: true }
  },
  {
    path: "/404",
    component: () => import("@/pages/error/404.vue"),
    meta: { hidden: true },
    alias: "/:pathMatch(.*)*"
  },
  {
    path: "/login",
    component: () => import("@/pages/login/index.vue"),
    meta: { hidden: true }
  },
  {
    path: "/",
    component: Layouts,
    redirect: "/dashboard",
    children: [
      {
        path: "dashboard",
        component: () => import("@/pages/dashboard/index.vue"),
        name: "Dashboard",
        meta: {
          title: "首页",
          svgIcon: "dashboard",
          affix: true
        }
      }
    ]
  }
]

/**
 * @name 动态路由
 * @description 修正后的三个核心模块路由，确保层级正确
 */
export const dynamicRoutes: RouteRecordRaw[] = [
  // 1. 系统管理模块
  {
    path: "/manager",
    component: Layouts,
    // 调整：默认不跳转三级路由，点击一级路由仅展开二级
    // redirect: "/system/enterprise-setting/enterprise-params",
    name: "System",
    meta: {
      title: "系统管理",
      roles: ["admin"],
      alwaysShow: true // 强制显示一级路由菜单
    },
    children: [
      // 二级路由：纯导航节点（无实际页面）
      {
        path: "system",
        component: EmptyNav, // 改用虚拟空组件
        name: "EnterpriseSetting",
        meta: {
          title: "企业设置",
          isNavOnly: true, // 标记为纯导航节点（用于侧边栏识别）
          alwaysShow: true
        },
        children: [
          // 三级路由：实际功能页面
          {
            path: "enterprise/index",
            component: () => import("@/pages/manager/system/enterprise/index.vue"),
            name: "EnterpriseParams",
            meta: { title: "企业参数设置" }
          },
          {
            path: "Logistics/index",
            component: () => import("@/pages/manager/system/Logistics/index.vue"),
            name: "Logistics",
            meta: { title: "物流参数设置" }
          }
        ]
      }
    ]
  },

  // 2. 数码管理模块
  {
    path: "/manager/code",
    component: Layouts,
    name: "CodeManagement",
    meta: {
      title: "数码管理",
      roles: ["admin"],
      alwaysShow: true
    },
    children: [
      // 二级路由：纯导航节点
      {
        path: "CodeMaking",
        component: Layouts, // 虚拟空组件
        name: "CodeMaking",
        meta: {
          title: "制码管理",
          isNavOnly: true,
          alwaysShow: true
        },
        children: [
          // 三级路由：实际功能页面
          {
            path: "index",
            component: () => import("@/pages/manager/code/CodeMaking/index.vue"), // 实际组件
            name: "CodeTask",
            meta: { title: "制码任务管理" }
          }
        ]
      }
    ]
  },

  // 3. 溯源管理模块
  {
    path: "/manager/trace",
    component: Layouts,
    name: "TraceManagement",
    meta: {
      title: "溯源管理",
      roles: ["admin"],
      alwaysShow: true
    },
    children: [
      // 二级路由：纯导航节点
      {
        path: "StorageArea",
        component: Layouts, // 虚拟空组件
        name: "StorageArea",
        meta: {
          title: "库区设置",
          isNavOnly: true,
          alwaysShow: true
        },
        children: [
          // 三级路由：实际功能页面
          {
            path: "index",
            component: () => import("@/pages/manager/trace/StorageArea/index.vue"), // 实际组件
            name: "StorageCategory",
            meta: { title: "库区类别管理" }
          }
        ]
      }
    ]
  }
]

/** 路由实例 */
export const router = createRouter({
  history: routerConfig.history,
  // routes: routerConfig.thirdLevelRouteCache
  //   ? flatMultiLevelRoutes([...constantRoutes, ...dynamicRoutes])
  //   : [...constantRoutes, ...dynamicRoutes]
  routes: [...constantRoutes, ...dynamicRoutes]
})

/** 重置路由 */
export function resetRouter() {
  try {
    router.getRoutes().forEach((route) => {
      const { name, meta } = route
      if (name && meta.roles?.length) {
        router.hasRoute(name) && router.removeRoute(name)
      }
    })
  } catch {
    location.reload()
  }
}

// 注册路由导航守卫
registerNavigationGuard(router)

// /**
//  * @name 动态路由
//  * @description 用来放置有权限 (Roles 属性) 的路由
//  * @description 必须带有唯一的 Name 属性
//  */
// export const dynamicRoutes: RouteRecordRaw[] = [
//   {
//     path: "/permission",
//     component: Layouts,
//     redirect: "/permission/page-level",
//     name: "Permission",
//     meta: {
//       title: "权限演示",
//       elIcon: "Lock",
//       // 可以在根路由中设置角色
//       roles: ["admin", "editor"],
//       alwaysShow: true
//     },
//     children: [
//       {
//         path: "page-level",
//         component: () => import("@/pages/demo/permission/page-level.vue"),
//         name: "PermissionPageLevel",
//         meta: {
//           title: "页面级",
//           // 或者在子路由中设置角色
//           roles: ["admin"]
//         }
//       },
//       {
//         path: "button-level",
//         component: () => import("@/pages/demo/permission/button-level.vue"),
//         name: "PermissionButtonLevel",
//         meta: {
//           title: "按钮级",
//           // 如果未设置角色，则表示：该页面不需要权限，但会继承根路由的角色
//           roles: undefined
//         }
//       }
//     ]
//   }
// ]
